/**
 * WebSocket客户端 - 用于接收任务进度推送
 * 
 * 使用说明：
 * 1. 安装依赖：npm install sockjs-client @stomp/stompjs
 * 2. 在前端组件中导入并使用此类
 * 3. 订阅特定任务的进度更新
 */

// @ts-ignore
import SockJS from 'sockjs-client';
import { Client, StompSubscription } from '@stomp/stompjs';

export interface TaskProgressInfo {
  taskId: number;
  progress: number;
  currentStage: string;
  message: string;
  isMilestone?: boolean;
  milestoneTitle?: string;
  milestoneDescription?: string;
  statistics?: { [key: string]: any };
  estimatedRemainingSeconds?: number;
  completedMilestones?: MilestoneInfo[];
  timestamp: number;
}

export interface MilestoneInfo {
  stage: string;
  title: string;
  description?: string;
  completedAt: number;
  progress: number;
  metrics?: { [key: string]: any };
}

export class TaskProgressWebSocketClient {
  private client: Client;
  private subscriptions: Map<number, StompSubscription> = new Map();
  private onProgressCallback?: (progress: TaskProgressInfo) => void;
  private onConnectionStatusCallback?: (connected: boolean) => void;

  constructor(private serverUrl?: string) {
    // 自动检测服务器URL
    if (!serverUrl) {
      // 开发环境：使用当前页面的origin（通过React代理）
      // 生产环境：也使用当前页面的origin（通过nginx代理）
      this.serverUrl = window.location.origin;
    } else {
      this.serverUrl = serverUrl;
    }

    console.log(`TaskProgressWebSocketClient: 连接到 ${this.serverUrl}/ws`);
    
    this.client = new Client({
      // 使用SockJS作为WebSocket的替代方案，通过代理访问
      webSocketFactory: () => new SockJS(`${this.serverUrl}/ws`),
      
      // 连接回调
      onConnect: () => {
        console.log('WebSocket连接成功');
        this.onConnectionStatusCallback?.(true);
      },
      
      // 断开连接回调
      onDisconnect: () => {
        console.log('WebSocket连接断开');
        this.onConnectionStatusCallback?.(false);
      },
      
      // 错误回调
      onStompError: (frame) => {
        console.error('WebSocket STOMP错误:', frame);
        this.onConnectionStatusCallback?.(false);
      },
      
      // 调试输出
      debug: (str) => {
        console.debug('WebSocket Debug:', str);
      },
      
      // 重连配置
      reconnectDelay: 5000,
      heartbeatIncoming: 4000,
      heartbeatOutgoing: 4000,
    });
  }

  /**
   * 连接到WebSocket服务器
   */
  connect(): void {
    if (!this.client.active) {
      this.client.activate();
    }
  }

  /**
   * 断开WebSocket连接
   */
  disconnect(): void {
    // 清理所有订阅
    this.subscriptions.forEach(subscription => subscription.unsubscribe());
    this.subscriptions.clear();
    
    // 断开连接
    if (this.client.active) {
      this.client.deactivate();
    }
  }

  /**
   * 订阅特定任务的进度更新
   */
  subscribeToTaskProgress(taskId: number, onProgress: (progress: TaskProgressInfo) => void): void {
    if (!this.client.active) {
      console.warn('WebSocket未连接，请先调用connect()方法');
      return;
    }

    // 如果已经订阅了该任务，先取消订阅
    const existingSubscription = this.subscriptions.get(taskId);
    if (existingSubscription) {
      existingSubscription.unsubscribe();
    }

    // 订阅任务进度频道
    const subscription = this.client.subscribe(
      `/topic/task/${taskId}/progress`,
      (message) => {
        try {
          const progressInfo: TaskProgressInfo = JSON.parse(message.body);
          console.log(`任务${taskId}进度更新:`, progressInfo);
          onProgress(progressInfo);
        } catch (error) {
          console.error('解析进度消息失败:', error);
        }
      }
    );

    this.subscriptions.set(taskId, subscription);
    console.log(`已订阅任务${taskId}的进度更新`);
  }

  /**
   * 取消订阅特定任务的进度更新
   */
  unsubscribeFromTaskProgress(taskId: number): void {
    const subscription = this.subscriptions.get(taskId);
    if (subscription) {
      subscription.unsubscribe();
      this.subscriptions.delete(taskId);
      console.log(`已取消订阅任务${taskId}的进度更新`);
    }
  }

  /**
   * 订阅所有任务的进度更新（管理员功能）
   */
  subscribeToAllProgress(onProgress: (progress: TaskProgressInfo) => void): void {
    if (!this.client.active) {
      console.warn('WebSocket未连接，请先调用connect()方法');
      return;
    }

    this.client.subscribe('/topic/progress', (message) => {
      try {
        const progressInfo: TaskProgressInfo = JSON.parse(message.body);
        console.log('全局进度更新:', progressInfo);
        onProgress(progressInfo);
      } catch (error) {
        console.error('解析全局进度消息失败:', error);
      }
    });
  }

  /**
   * 查询特定任务的当前进度
   */
  queryTaskProgress(taskId: number): void {
    if (!this.client.active) {
      console.warn('WebSocket未连接，无法查询进度');
      return;
    }

    this.client.publish({
      destination: `/app/task/${taskId}/query-progress`,
      body: JSON.stringify({ taskId })
    });
  }

  /**
   * 发送ping保持连接
   */
  ping(): void {
    if (!this.client.active) {
      return;
    }

    this.client.publish({
      destination: '/app/ping',
      body: 'ping'
    });
  }

  /**
   * 设置连接状态回调
   */
  setConnectionStatusCallback(callback: (connected: boolean) => void): void {
    this.onConnectionStatusCallback = callback;
  }

  /**
   * 获取连接状态
   */
  isConnected(): boolean {
    return this.client.connected;
  }
}

// 使用示例：

/*
// 1. 创建WebSocket客户端
const wsClient = new TaskProgressWebSocketClient();

// 2. 设置连接状态监听
wsClient.setConnectionStatusCallback((connected) => {
  if (connected) {
    console.log('WebSocket已连接');
    // 连接成功后订阅任务进度
    wsClient.subscribeToTaskProgress(taskId, handleTaskProgress);
  } else {
    console.log('WebSocket已断开');
  }
});

// 3. 连接到服务器
wsClient.connect();

// 4. 处理进度更新
function handleTaskProgress(progress: TaskProgressInfo) {
  console.log('收到进度更新:', progress);
  
  // 更新UI
  if (progress.isMilestone) {
    // 显示里程碑信息
    showMilestone(progress.milestoneTitle, progress.milestoneDescription);
  } else {
    // 更新进度条
    updateProgressBar(progress.progress, progress.message);
  }
  
  // 显示预估时间
  if (progress.estimatedRemainingSeconds) {
    showEstimatedTime(progress.estimatedRemainingSeconds);
  }
}

// 5. 组件销毁时清理
// wsClient.unsubscribeFromTaskProgress(taskId);
// wsClient.disconnect();
*/